package br.com.tecnoria.controllers
{
	
	import br.com.tecnoria.vo.AddressVO;
	import br.com.tecnoria.vo.CustomerVO;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.mxml.RemoteObject;
	
	import org.swizframework.utils.services.ServiceHelper;
	
	public class AddressController
	{
		[Inject("addressRemote")]
		public var remote:RemoteObject;
		
		[Inject]
		public var serviceHelper:ServiceHelper;
		
		[Bindable]
		public var dataprovider:ArrayCollection;
		
		[Bindable]
		public var address:AddressVO;
		
		[Bindable]
		[Inject(source="customerController.customer", bind="true")]
		public var customer:CustomerVO;
		
		
		
		/**
		 * Call Function
		 */
		
		[EventHandler(event="AddressEvent.SAVE", properties="address")]
		public function saveAddress(address:AddressVO):void
		{
			serviceHelper.executeServiceCall(remote.saveAddress(address), onSaveAddress, onFault);
		}
		
		[EventHandler(event="AddressEvent.LIST", properties="customer")]
		public function listAddress(customer:CustomerVO):void
		{
			serviceHelper.executeServiceCall(remote.listAddress(customer), onListAddress, onFault);
		}
		
		[EventHandler(event="AddressEvent.UPDATE", properties="address")]
		public function updateAddress(address:AddressVO):void
		{
			serviceHelper.executeServiceCall(remote.updateAddress(address), onUpdateAddress, onFault);
		}
		
		[EventHandler(event="AddressEvent.DELETE", properties="address")]
		public function deleteAddress(address:AddressVO):void
		{
			serviceHelper.executeServiceCall(remote.deleteAddress(address), onDeleteAddress, onFault);
		}
		
		
		/**
		 * Result Function
		 */
		
		public function onSaveAddress(result:ResultEvent):void
		{
			address = new AddressVO(result.result);
			listAddress(customer);
		}
		
		public function onListAddress(result:ResultEvent):void
		{
			dataprovider = new ArrayCollection(result.result as Array);
		}
		
		public function onUpdateAddress(result:ResultEvent):void
		{
			address = new AddressVO(result.result);
		}
		
		public function onDeleteAddress(result:ResultEvent):void
		{
			listAddress(customer);
		}
		
		
		
		/**
		 * Fault Function
		 */
		
		public function onFault(result:FaultEvent):void
		{
			Alert.show(result.fault.toString(), "Erro");
		}
	}
}